<template>
  <div clsas="main-container">
    <div class="banner-and-menu">
      <!-- 轮播图 -->
      <BannerList v-if="bannerInfo.length > 0" style="width: 1200px; margin: 0 auto" :bannerInfo="bannerInfo">
      </BannerList>

    </div>
    <!-- 菜单栏 -->
    <div ref="menuRef" class="menu-container">
      <div class="menu-list">
        <ul class="menu">
          <li :class="$route.path === '/home/recommend' ? 'active' : ''">
            <RouterLink to="/home/recommend">推荐</RouterLink>
          </li>

          <li :class="$route.path === '/home/production' ? 'active' : ''">
            <RouterLink to="/home/production">作品</RouterLink>
          </li>

          <li :class="$route.path === '/home/tutorial' ? 'active' : ''">
            <RouterLink to="/home/tutorial">教程</RouterLink>
          </li>

          <li :class="$route.path === '/home/subject' ? 'active' : ''">
            <RouterLink to="/home/subject">专题</RouterLink>
          </li>

          <li :class="$route.path === '/home/dynamic' ? 'active' : ''">
            <RouterLink to="/home/dynamic">动态</RouterLink>
          </li>

          <li :class="$route.path === '/home/attention' ? 'active' : ''">
            <RouterLink to="/home/attention">关注</RouterLink>
          </li>
        </ul>
        <div class="hobby">
          <i class="iconfont icon-yingyong" style="font-size: 24px;"></i>
          <a href="javascript:;" @click="showDialog">选择兴趣爱好</a>
        </div>
      </div>
    </div>

    <div class="subPage">
      <RouterView></RouterView>
      <!-- 回到顶部 -->
      <div v-show="isShowBackIcon" class="back-top-icon" @click="smoothBackTop">
      </div>
    </div>



    <!-- 选择兴趣爱好对话框 -->
    <el-dialog v-model="dialogVisible" :title="searchData.length ? '搜索结果' : `选择我的兴趣技能 ${hobbyArr.length} / 7` " width="1040px"
      :before-close="handleClose">
      <!-- <div>111222</div> -->
      <!-- 搜索输入框区域 -->
      <el-form :inline="true">
        <el-form-item>
          <el-input @input="searchResult" v-model="searchKeyword" style="width: 300px" placeholder="搜索兴趣技能"
            size="large"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button :disabled="!searchKeyword.trim().length" style="width: 80px" @click="searchResult">搜索</el-button>
        </el-form-item>
      </el-form>

      <div v-if="!searchData.length">
        <!-- 如果hobbyArr有值，那么就渲染，如果没有就不渲染 -->
        <ul v-show="hobbyArr.length" class="hobby-arr">
          <li class="hobby-item" v-for="selHobby in hobbyArr" :key="selHobby.id">
            {{ selHobby.name }}
            <span class="close-icon" @click="delHobby(selHobby)">✖</span>
          </li>
        </ul>
        <!-- 推荐兴趣技能列表 -->
        <div class="mb-10">推荐兴趣技能</div>
        <div v-infinite-scroll="load" :infinite-scroll-immediate="false" class="hobby-list-containr">
          <ul class="recommend-hobby-list mt-20">
            <li class="hobby-item" v-for="hobby in allHobbyArr" :key="hobby.id" :title="hobby.name"
              @click="addHobby(hobby)">
              {{ hobby.name }}
              <span v-show="hobby.isSelect" class="select-icon">✔</span>
            </li>
          </ul>
        </div>
      </div>

      <!-- 搜索结果展示的对话框 -->
      <div v-else>
        <div class="mb-20">搜索结果</div>
        <ul class="search-reuslt">
          <li v-for="data in searchData" :key="data.id" @click="addHobby(data)">
            <h4>{{ data.name }}</h4>
            <p>{{ data.description }}</p>
          </li>
        </ul>
      </div>


      <!-- 取消和确定按钮 -->
      <template #footer>
        <span class="dialog-footer" v-if="!searchData.length">
          <el-button plain class="dialog-btn" @click="onCancel">取消</el-button>
          <el-button color="#F93684" type="primary" @click="onSave">确定</el-button>
        </span>
        <span v-else>
          <el-button type="success" @click="goBack">返回</el-button>
        </span>
      </template>
    </el-dialog>


  </div>
</template>

<script setup lang='ts'>
import BannerList from '@/components/BannerList/index.vue';
import { nextTick, onMounted, ref } from 'vue';
import { RouterLink, RouterView } from 'vue-router';
import { getBannerlistInfo } from '@/api/home';
import { getHobbyListData, getSearchData } from '@/api/hobby';
import { useRoute } from 'vue-router';
const route = useRoute();


const addSearchRes = (data:any) => {
  console.log(data);
}

// 点击回到顶部按钮平滑回到顶部
const smoothBackTop = () => {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  });
}


// 二级菜单元素
const menuRef = ref();
const isShowBackIcon = ref(false);

// 当页面滚动时触发的回调
window.onscroll = () => {
  if (route.path !== '/home/recommend') {
    return;
  }
  // 获取二级菜单元素相对于视口的顶部距离
  const { top } = menuRef.value.getBoundingClientRect();
  // 如果顶部距离为0，添加阴影，反之就不添加
  if (!top) {
    menuRef.value.style.boxShadow = '0 2px 10px rgba(0, 0, 0, .2)';
    isShowBackIcon.value = true;
  } else {
    menuRef.value.style.boxShadow = 'none';
    isShowBackIcon.value = false;
  }
}

// window.onresize = () => {
//   console.log('111');
// }


// 保存轮播图数据
const bannerInfo = ref([]);
// 获取轮播图数据
const getBannerInfo = async () => {
  try {
    const { data } = await getBannerlistInfo();
    nextTick(() => {
      bannerInfo.value = data;
    })
  } catch (error) {
    console.error(error);
  }
}


// 是否显示对话框的布尔值
const dialogVisible = ref(false);
// 是否选中兴趣标签的布尔值
const isSelect = ref(false);
// 用来选中的渲染兴趣列表的数组
const hobbyArr = ref<any[]>([]);
// 用于中间传递已选中兴趣列表的数组的数据
const passHobbyArr = ref<any[]>([]);
// 用来渲染全部兴趣列表的数组
const allHobbyArr = ref<any[]>([]);
const searchKeyword = ref('');  // 搜索的关键字
// 保存搜索的数据
const searchData = ref<any[]>([]);

const pageNum = ref(1);
const PageSize = ref(20);

// 搜索框实时输入的回调
const searchResult = async () => {
  if (!searchKeyword.value.trim().length) {
    return;
  }

  // 根据输入的关键字发送请求获取数据
  try {
    const { data } = await getSearchData(searchKeyword.value.trim());
    data.forEach((item:any) => {
      item.isSelect = false;
    })
    searchData.value = data;
  } catch (error) {
    console.error(error);
  }
}

// 返回兴趣标签列表页的回调
const goBack = () => {
  // 清空搜索结果数组和关键字
  searchData.value = [];
  searchKeyword.value = '';
};

// 关闭对话框之前的回调
const handleClose = (done: () => void) => {
  // 关闭之前清除对话框内容
  onCancel();
  done();
}


// 获取兴趣标签列表数据的回调
const getHobbyListInfo = async (num: number = 0, size: number = 40) => {
  try {
    const { data } = await getHobbyListData(num, size);
    // 获取数据后对每个数据中的值添加一个是否选中的状态
    data.content.forEach((item: any, index: number) => {
      item.isSelect = false;
    })
    allHobbyArr.value.push(...data.content);
  } catch (error) {
    console.error(error);
  }
}

// 显示对话框的回调
const showDialog = async () => {
  dialogVisible.value = true;
  hobbyArr.value = [...passHobbyArr.value];
  // 发送请求获取数据用于渲染列表
  await getHobbyListInfo();
  // 双层遍历找到当前已选择兴趣标签数组中对应的数据,把数据的选中状态改变
  hobbyArr.value.forEach((item: any, index: number) => {
    allHobbyArr.value.forEach((item2: any, index: number) => {
      if (item.name === item2.name) {
        item2.isSelect = true;
      }
    })
  })
}

// 滚动的回调
const load = () => {
  // 走到这个函数表示滚动条到底了
  // 发送请求获取下一页的数据
  getHobbyListInfo(++pageNum.value, PageSize.value);
}

// 取消按钮的回调
const onCancel = () => {
  // 清除对话框全部兴趣列表内容
  allHobbyArr.value = [];
  hobbyArr.value = [];
  // 关闭对话框
  dialogVisible.value = false;
}

// 确定按钮的回调
const onSave = () => {
  // 清除全部兴趣标签数组 和关闭对话框
  allHobbyArr.value = [];
  // 点击保存按钮的时候另存一份
  passHobbyArr.value = hobbyArr.value;
  hobbyArr.value = [];
  // 关闭对话框
  dialogVisible.value = false;
}

// 添加兴趣标签
const addHobby = (hobby: any) => {
  if (hobbyArr.value.length === 7 && !hobby.isSelect) {
    alert('最多只能添加7个');
    return
  }
  if (hobby.isSelect) {
    // console.log('删除', hobby.isSelect);
    // 修改当前点击的兴趣标签的选中状态
    // hobby.isSelect = false;
    // 删除当前点击的兴趣标签
    hobbyArr.value.forEach((item: any, index: number) => {
      if (item.name === hobby.name) {
        hobbyArr.value.splice(index, 1);
      }
    })
    const allItem = allHobbyArr.value.find(item => item.name === hobby.name);
    if (allItem) {
      allItem.isSelect = false;
    }
  } else {
    // 针对搜索功能判断添加是否重复
    const isRepeat = hobbyArr.value.findIndex(item => item.name === hobby.name);
    if (isRepeat >= 0) {
      alert('已添加');
      return;
    }
    // console.log('增加', hobby.isSelect);
    // 修改当前点击的兴趣标签的选中状态
    hobby.isSelect = true;
    // 向 hobbyArr 数组中添加选中的兴趣标签
    hobbyArr.value.push(hobby);
    // 显示兴趣列表页面
    searchData.value = [];
    // 清空输入框内容
    searchKeyword.value = '';
  }
}


// 删除兴趣标签的回调
const delHobby = (selHobby: any) => {
  addHobby(selHobby);
}

// 在页面挂载之后发送请求获取数据获取轮播图数据
onMounted(() => {
  getBannerInfo();
})


</script>

<style lang="less" scoped>
// .main-container {
//   position: relative;
// }

.banner-and-menu {
  width: 1200px;
  margin: 0 auto;
}

.menu-container {
  position: sticky;
  top: 0;
  background-color: #fff;

  .menu-list {
    position: relative;
    display: flex;
    justify-content: center;
    height: 70px;
    width: 1200px;
    margin: 0 auto;

    .menu {
      display: flex;
      align-items: center;

      li {
        line-height: 50px;
        margin: 0 20px;

        a {
          text-decoration: none;
          color: #000;
        }
      }

      li.active {
        border-bottom: 3px solid #000;
      }
    }

    .hobby {
      position: absolute;
      right: 0;
      line-height: 70px;
      display: flex;
      align-items: center;

      .icon {
        width: 26px;
        height: 30px;
      }

      a {
        text-decoration: none;
        color: #000;
        margin-left: 10px;
      }
    }
  }



}

// 二级页面的背景颜色和居中显示
.subPage {
  background-color: #F5F7F9;
  padding: 20px 0;

  div,
  ul {
    width: 1200px;
    margin: 0 auto;
  }

  // 回到顶部的图标
  .back-top-icon {
    position: sticky;
    bottom: 40px;
    width: 40px;
    height: 40px;
    margin-left: 1600px;
    background: url('@/assets/images/back_top@3x.e71cd044.png') no-repeat center;
    cursor: pointer;
  }
}

// 对话框样式
.el-button {
  width: 130px;
  padding: 20px 0;
}

.el-button.dialog-btn:hover {
  width: 130px;
  padding: 20px 0;
  color: #F93684;
  border: 1px solid #fb66a2;
  background-color: #FEEBF3;
}


.hobby-list-containr {
  width: 100%;
  height: 340px;
  // border: 1px solid red;
  overflow: auto;
}

.hobby-arr,
.recommend-hobby-list {
  display: flex;
  // padding: 10px 0;
  flex-wrap: wrap;

  // 叉号样式
  .close-icon {
    position: absolute;
    top: -8px;
    right: -8px;
    text-align: center;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background-color: #aaa;
    color: #fff;
    cursor: pointer;
  }

  // 对号样式
  .select-icon {
    position: absolute;
    top: -8px;
    right: -8px;
    text-align: center;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background-color: #F93684;
    color: #fff;
    cursor: pointer;
  }
}

.hobby-item {
  position: relative;
  width: 70px;
  text-align: center;
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 10px 20px;
  margin: 0 33px 20px 0;
  font-size: 12px;
  color: #000;
  cursor: pointer;

}

.hobby-item:nth-child(7n) {
  margin-right: 0;
}

.search-reuslt {
  display: flex;
  // justify-content: center;
  flex-wrap: wrap;

  li {
    width: 280px;
    min-height: 48px;
    padding: 10px;
    background-color: #F5F7F9;
    border-radius: 5px;
    margin-right: 20px;
    margin-bottom: 20px;
    cursor: pointer;
    &:hover {
      background-color: rgba(0, 0, 0, .1);
    }

    h4 {
      font-size: 18px;
      color: #999;
      margin-bottom: 4px;
    }

    p {
      font-size: 16px;
    }
  }

  li:nth-child(3n) {
    margin-right: 0;
  }
}
</style>